<template>
  <div class="dashboard-container">
    <!-- 顶部标题栏 -->
    <a-row class="header" :gutter="16">
      <a-col :span="24">
        <div class="title">实时监控与数据分析</div>
      </a-col>
    </a-row>

    <!-- 第一行：关键指标 -->
    <a-row class="metrics-row" :gutter="16">
      <a-col :xs="24" :sm="12" :md="6" v-for="(item, index) in metrics" :key="index">
        <a-card class="metric-card" :head-style="{background: item.color}">
          <template #title>
            <div class="metric-title">
              <component :is="item.icon" />
              <span>{{ item.title }}</span>
            </div>
          </template>
          <div class="metric-content">
            <div class="metric-value">{{ item.value }}</div>
            <div class="metric-trend">
              <span :class="item.trend > 0 ? 'up' : 'down'">
                {{ item.trend > 0 ? '↑' : '↓' }} {{ Math.abs(item.trend) }}%
              </span>
              <span class="metric-unit">{{ item.unit }}</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 第二行：主要图表 -->
    <a-row class="chart-row" :gutter="16">
      <!-- 安全事故统计 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card title="安全事故统计" class="chart-card">
          <div ref="accidentChart" class="chart"></div>
        </a-card>
      </a-col>
      
      <!-- 隐患类型分布 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="12">
        <a-card title="隐患类型分布" class="chart-card">
          <div ref="riskChart" class="chart"></div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 第三行：底部图表 -->
    <a-row class="chart-row" :gutter="16">
      <!-- 整改完成率 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="8">
        <a-card title="整改完成率" class="chart-card">
          <div ref="completionChart" class="chart"></div>
        </a-card>
      </a-col>
      
      <!-- 安全检查频次 -->
      <a-col :xs="24" :sm="24" :md="12" :lg="8">
        <a-card title="安全检查频次" class="chart-card">
          <div ref="inspectionChart" class="chart"></div>
        </a-card>
      </a-col>
      
      <!-- 设备运行状态 -->
      <a-col :xs="24" :sm="24" :md="24" :lg="8">
        <a-card title="设备运行状态" class="chart-card">
          <div ref="equipmentChart" class="chart"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import {
  AlertOutlined,
  SafetyCertificateOutlined,
  BarChartOutlined,
  LineChartOutlined,
  // PieChartOutlined
} from '@ant-design/icons-vue';

// 响应式调整图表大小
const resizeCharts = () => {
  charts.forEach(chart => {
    chart?.resize();
  });
};
const useResponsiveChart = (chartRef: Ref<HTMLElement | undefined>, option: any) => {
  const chart = ref<echarts.ECharts>();
  
  const initChart = () => {
    if (chartRef.value) {
      chart.value = echarts.init(chartRef.value);
      chart.value.setOption(option);
      charts.push(chart.value);
    }
  };

  const resizeChart = () => {
    chart.value?.resize();
  };

  onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart);
  });

  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
    chart.value?.dispose();
  });

  return { chart };
};

// 关键指标数据
const metrics = ref([
  { title: '安全生产天数', value: 365, trend: 12.5, unit: '天', color: '#1890ff', icon: SafetyCertificateOutlined },
  { title: '隐患数量', value: 28, trend: -5.3, unit: '个', color: '#faad14', icon: AlertOutlined },
  { title: '整改完成率', value: 92, trend: 3.2, unit: '%', color: '#52c41a', icon: BarChartOutlined },
  { title: '事故发生率', value: 0.8, trend: -1.5, unit: '‰', color: '#f5222d', icon: LineChartOutlined }
]);

// ECharts实例
const accidentChart = ref<HTMLElement>();
const riskChart = ref<HTMLElement>();
const completionChart = ref<HTMLElement>();
const inspectionChart = ref<HTMLElement>();
const equipmentChart = ref<HTMLElement>();
const charts: echarts.ECharts[] = [];

onMounted(() => {
  // 初始化图表
  initAccidentChart();
  initRiskChart();
  initCompletionChart();
  initInspectionChart();
  initEquipmentChart();
  
  // 监听窗口变化
  window.addEventListener('resize', resizeCharts);
});

onBeforeUnmount(() => {
  // 移除监听并销毁图表
  window.removeEventListener('resize', resizeCharts);
  charts.forEach(chart => chart?.dispose());
});

// 初始化安全事故统计图表
const initAccidentChart = () => {
  const chart = echarts.init(accidentChart.value!);
  
  charts.push(chart);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      axisLine: {
        lineStyle: { color: '#d9d9d9' }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: { color: '#d9d9d9' }
      },
      splitLine: {
        lineStyle: { type: 'dashed' }
      }
    },
    series: [
      {
        name: '事故数量',
        type: 'bar',
        barWidth: '60%',
        data: [5, 8, 6, 10, 7, 4, 3, 2, 1, 4, 3, 2],
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#1890ff' },
            { offset: 1, color: '#36cbcb' }
          ])
        }
      }
    ]
  };
  
  chart.setOption(option);
   useResponsiveChart(accidentChart, option);
};

// 初始化隐患类型分布图表
const initRiskChart = () => {
  const chart = echarts.init(riskChart.value!);
  charts.push(chart);
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '隐患类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: '电气隐患' },
          { value: 28, name: '消防隐患' },
          { value: 22, name: '机械隐患' },
          { value: 15, name: '化学品隐患' }
        ],
        color: ['#1890ff', '#36cbcb', '#13c2c2', '#52c41a']
      }
    ]
  };
  
  chart.setOption(option);
     useResponsiveChart(riskChart, option);
};

// 初始化整改完成率图表（仪表盘）
const initCompletionChart = () => {
  const chart = echarts.init(completionChart.value!);
  charts.push(chart);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}%'
    },
    series: [{
      name: '整改完成率',
      type: 'gauge',
      progress: {
        show: true,
        width: 12
      },
      detail: {
        valueAnimation: true,
        formatter: '{value}%',
        fontSize: 16
      },
      data: [{
        value: 92,
        name: '完成率'
      }],
      axisLine: {
        lineStyle: {
          width: 12,
          color: [
            [0.3, '#f5222d'],
            [0.7, '#faad14'],
            [1, '#52c41a']
          ]
        }
      },
      axisTick: {
        distance: -15,
        length: 6
      },
      splitLine: {
        distance: -15,
        length: 10
      }
    }]
  };
  
  chart.setOption(option);
       useResponsiveChart(completionChart, option);
};

// 初始化安全检查频次图表（折线图）
const initInspectionChart = () => {
  const chart = echarts.init(inspectionChart.value!);
  charts.push(chart);
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月'],
      axisLine: {
        lineStyle: {
          color: '#d9d9d9'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#d9d9d9'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      data: [12, 18, 15, 20, 16, 22],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3,
        color: '#1890ff'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24, 144, 255, 0.5)' },
          { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
        ])
      }
    }]
  };
  
  chart.setOption(option);
         useResponsiveChart(inspectionChart, option);
};

// 初始化设备运行状态图表（饼图）
const initEquipmentChart = () => {
  const chart = echarts.init(equipmentChart.value!);
  charts.push(chart);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [{
      name: '设备状态',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 78, name: '正常运行' },
        { value: 15, name: '待检修' },
        { value: 7, name: '故障中' }
      ],
      color: ['#52c41a', '#faad14', '#f5222d']
    }]
  };
  
  chart.setOption(option);
           useResponsiveChart(equipmentChart, option);
};

</script>

<style scoped lang="scss">
.dashboard-container {
  height: 100%;
  padding: 10px;
  background-color: #fff;
  overflow-y: auto;
  
  .header {
    margin-bottom: 16px;
    text-align: center;
    
    .title {
      font-size: 24px;
      font-weight: bold;
      color: #1890ff;
    }
    
    .subtitle {
      font-size: 16px;
      color: #666;
    }
  }
  
  .metrics-row {
    margin-bottom: 16px;
    
    .metric-card {
      height: 100%;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      
      .metric-title {
        display: flex;
        align-items: center;
          color: #fff;
        :deep(svg) {
          margin-right: 8px;
          font-size: 18px;
        }
      }
      
      .metric-content {
        padding: 8px 0;
        
        .metric-value {
          font-size: 28px;
          font-weight: bold;
          color: #333;
        }
        
        .metric-trend {
          margin-top: 8px;
          font-size: 14px;
          
          .up {
            color: #f5222d;
          }
          
          .down {
            color: #52c41a;
          }
          
          .metric-unit {
            margin-left: 4px;
            color: #999;
          }
        }
      }
    }
  }
  
  .chart-row {
    margin-bottom: 16px;
    
    .chart-card {
      height: 100%;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      
      .chart {
        width: 100%;
        height: 300px;
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 8px;
    
    .chart-card {
      margin-bottom: 16px;
    }
  }
}
</style>